package com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.feedback

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication

import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.IApiProcessCameroonCallback
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.createApiActionCameroon
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.doPostRequestCameroon
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.doUploadImageCameroon
import com.helasasa.maxfunds.lineofcredit.cashloan.utils.imageUtil.ImageConvert
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream

class FeedbackCameroonViewModel : ViewModel() {

    private val _loadingResult = MutableLiveData<Boolean>()
    val loadingResult: LiveData<Boolean> = _loadingResult

    private val _pageDetailResult = MutableLiveData<FeedbackCameroonResult>()
    val pageDetailResult: LiveData<FeedbackCameroonResult> = _pageDetailResult

    private val _saveFeedbackResult = MutableLiveData<FeedbackCameroonSaveResult>()
    val saveFeedbackResult: LiveData<FeedbackCameroonSaveResult> = _saveFeedbackResult

    /**
     * 切换type类型
     */
    fun typeChanged(type: String) {
        val input = _pageDetailResult.value?.input
        val picUrls = _pageDetailResult.value?.picUrls
        val picBitmaps = _pageDetailResult.value?.picBitmaps
        _pageDetailResult.value = FeedbackCameroonResult(
            type = type,
            input = input,
            picUrls = picUrls,
            picBitmaps = picBitmaps
        )
    }

    /**
     * 输入变化
     */
    fun inputChanged(input: String) {
        val type = _pageDetailResult.value?.type ?: "SUGGEST"
        val picUrls = _pageDetailResult.value?.picUrls
        val picBitmaps = _pageDetailResult.value?.picBitmaps
        _pageDetailResult.value = FeedbackCameroonResult(
            type = type,
            input = input,
            picUrls = picUrls,
            picBitmaps = picBitmaps
        )
    }

    /**
     * 删除图片
     */
    fun deletePic(index: Int = 0) {
        val type = _pageDetailResult.value?.type ?: "SUGGEST"
        val input = _pageDetailResult.value?.input
        val picUrls = _pageDetailResult.value?.picUrls ?: mutableListOf()
        val picBitmaps = _pageDetailResult.value?.picBitmaps ?: mutableListOf()

        if (picUrls.size > index) {
            picUrls.removeAt(index)
        }

        if (picBitmaps.size > index) {
            picBitmaps.removeAt(index)
        }

        _pageDetailResult.value = FeedbackCameroonResult(
            type = type,
            input = input,
            picUrls = picUrls,
            picBitmaps = picBitmaps
        )
    }

    /**
     * 重置
     */
    fun reset() {
        val input = null
        val picUrls = null
        val picBitmaps = mutableListOf<Bitmap>()
        _pageDetailResult.value = FeedbackCameroonResult(
            type = "SUGGEST",
            input = input,
            picUrls = picUrls,
            picBitmaps = picBitmaps
        )
    }

    /**
     * 保存信息
     */
    fun saveFeedbackInfo() {
        _loadingResult.value = true
        val type = _pageDetailResult.value?.type ?: "SUGGEST"
        val input = _pageDetailResult.value?.input
        val picUrls = _pageDetailResult.value?.picUrls ?: mutableListOf()
        if (input.isNullOrBlank()) {
            _saveFeedbackResult.value =
                FeedbackCameroonSaveResult(error = "Please input feedback content")
            return
        }

        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiActionCameroon()
        action["path"] = "ajMne59tlFn2zOySdq4cw"
        action["type"] = type
        action["opinion"] = input
        action["images"] = picUrls.joinToString(",")

        context.doPostRequestCameroon(action, object : IApiProcessCameroonCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false
                _saveFeedbackResult.value = FeedbackCameroonSaveResult(success = true)
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false
                _saveFeedbackResult.value = FeedbackCameroonSaveResult(error = errMsg)
            }
        })

    }

    /**
     * 处理图片uri
     */
    @SuppressLint("Recycle")
    fun handlePickImageResult(context: Context, result: Uri?) {
        try {
            println(result.toString())
            result?.let {
                val path = imageUriToLocalFile(context, it)
                //压缩图片
                ImageConvert.startConvertImage(File(path)) { localPath, thumpImg ->
                    updateImageResult(localPath, thumpImg)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 处理图片path
     */
    fun handleTakePictureResult(result: String?) {
        try {
            println(result.toString())
            result?.let {
                val localPath = it
                val thumpImg = imagePathToBitmap(localPath)
                updateImageResult(localPath, thumpImg)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 上传图片
     */
    private fun uploadImage(filePath: String, type: Int = 0) {
        _loadingResult.value = true
        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>()
        action["filePath"] = filePath
        action["cardType"] = type.toString()

        context.doUploadImageCameroon(action, object : IApiProcessCameroonCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false
                val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                val url = obj.optString("url")
                if (url.isNotBlank()) {
                    uploadImageResult(url, type)
                } else {
                    uploadImageResult(null, type)
                }
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false
                uploadImageResult(null, type, errMsg)
            }
        })
    }

    /**
     * 上传图片回显
     */
    private fun uploadImageResult(url: String?, cardType: Int = 0, error: String? = null) {
        try {
            if (url == null) {
                _pageDetailResult.value = FeedbackCameroonResult(error = error)
                return
            }

            val type = _pageDetailResult.value?.type ?: "SUGGEST"
            val input = _pageDetailResult.value?.input
            val picUrls = _pageDetailResult.value?.picUrls ?: mutableListOf()
            val picBitmaps = _pageDetailResult.value?.picBitmaps ?: mutableListOf()

            val picUrlsResult = mutableListOf<String>()
            if (picUrls.size > 0) {
                picUrlsResult.add(picUrls[0])
                picUrlsResult.add(url)
            } else {
                picUrlsResult.add(url)
            }

            _pageDetailResult.value = FeedbackCameroonResult(
                type = type,
                input = input,
                picUrls = picUrlsResult,
                picBitmaps = picBitmaps
            )

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 更新图片显示
     */
    private fun updateImageResult(localPath: String, thumpImg: Bitmap) {
        try {
            val type = _pageDetailResult.value?.type ?: "SUGGEST"
            val input = _pageDetailResult.value?.input

            val picUrls = _pageDetailResult.value?.picUrls ?: mutableListOf()
            val picBitmaps = _pageDetailResult.value?.picBitmaps ?: mutableListOf()

            if (picBitmaps.size < 2) {
                picUrls.add(localPath)
                picBitmaps.add(thumpImg)
            }

            _pageDetailResult.value = FeedbackCameroonResult(
                type = type,
                input = input,
                picUrls = picUrls,
                picBitmaps = picBitmaps
            )

            // 上传图片
            uploadImage(localPath)

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun imageUriToLocalFile(
        context: Context,
        contentURI: Uri
    ): String {
        try {
            println(contentURI.path)

            val imgDir = "${
                ProjectApplication.context.applicationContext.filesDir
            }${File.separator}${ProjectApplication.mProduct}_IAGS"

            val dirFile = File(imgDir)
            if (!dirFile.exists()) {
                dirFile.mkdirs()
            }

            val outFilePath = "$imgDir/${System.currentTimeMillis()}.jpg"
            val imgInputStream: InputStream =
                context.contentResolver.openInputStream(contentURI) ?: return ""
            val outFile = File(outFilePath)
            val buffer = ByteArray(1024)
            var len: Int
            val fos = FileOutputStream(outFile)
            while (imgInputStream.read(buffer).also { len = it } != -1) {
                fos.write(buffer, 0, len)
            }
            fos.flush()
            fos.close()
            imgInputStream.close()
            return outFilePath
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    private fun imagePathToBitmap(filePath: String?): Bitmap {
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = false
        return BitmapFactory.decodeFile(filePath, options)
    }
}